import { defineStore } from 'pinia'

import { PREFIX } from '~utils/util'

const valueMap = (state, key) => {
  if(state.dictionary[key] === undefined) {
    return {}
  }

  const map = {}
  state.dictionary[key].data.forEach(item => {
    map[item.value] = item.label
  })
  return map
}

const useDictionaryStore = defineStore('dictionary', {
  state: () => ({
    dictionary: {}
  }),
  getters: {
    gender: (state) => valueMap(state, 'gender'),
    userStatus: (state) => valueMap(state, 'user_status'),
    role: (state) => valueMap(state, 'role'),
    articleStatus: (state) => valueMap(state, 'article_status')
  },
  actions: {
    setDictionary(data) {
      this.dictionary = data
    }
  },
  persist: {
    key: `${PREFIX}|dictionary`,
    storage: window.sessionStorage,
    paths: ['dictionary']
  }
})

export default useDictionaryStore
